import Joi from 'joi';

/**
 * 重新构建 Joi 的 Schema 方便在 Mongo 查询
 *   - 去除 required 属性
 *   - Array 转为 Object
 * @param {Object} Joi Schema 对象
 * @return {Object} Joi Schema 对象
 */
export default function joiToFilterArg(x) {
	let schema = x;
	while (schema.type === 'array') {
		schema = schema.$_terms.items[0];
	}

	let ret;
	switch (schema.type) {
		case 'string':
			ret = Joi.string();
			break;
		case 'number':
			ret = Joi.number();
			break;
		case 'date':
			ret = Joi.date();
			break;
		case 'boolean':
			ret = Joi.boolean();
			break;
		case 'any':
			ret = Joi.any();
			break;
		default:
			ret = Joi.object();
			// eslint-disable-next-line no-unused-expressions
			schema.$_terms.keys?.forEach(({ key, schema }) => {
				ret = ret.append({
					[key]: joiToFilterArg(schema),
				});
			});
	}

	const description = schema._flags.description;
	if (description) {
		ret = ret.description(description);
	}

	if (schema._flags.unknown) {
		ret = ret.unknown();
	}

	return ret;
}
